jQuery(function(){
  var $form = jQuery('#login-form');
  
  jQuery('button',$form).each(function(){
    var $this = jQuery(this);
    var logout=false;
    var pars  =null;
    
    switch($this.attr('value')){
      case 'retrieve':
      case 'login':
        pars = {"icons" : {"primary" : "ui-icon-key"}};
        break;
      case 'oups':
        pars = {"icons" : {"primary" : "ui-icon-shuffle"}};
        $this.click(function(){
          $form.find('#login-ident, #login-retrieve').slideToggle(200);
        });
        break;
      case 'admin':
        pars = {"icons" : {"primary" : "ui-icon-contact"}};
        logout=false;
        $this.click(function(){
          com.lolita.dialog.player($this.data('id'));
        });
        break;
      case 'logout':
        pars = {"icons" : {"primary" : "ui-icon-circle-close"}};
        logout=true;
        break;
    }
    
    if(logout==true){
      var $link = $this.find('a');
      $this.text($link.hide().text());
      $this.click(function(){
        window.location.replace($link.attr('href'));
      });
      
    }
    
    if(pars){
      $this.button(pars);
    }
    
  });
  var to=0;
  
  var hideForm = function(){
    $form.removeClass('visible').slideUp(200);
    clearTimeout(to); to=0;
  }
  
  $form.closest('li').hover(function(event){
    $form.stop(true,true);
    clearTimeout(to);
    $form.slideDown('500',function(){
      $form.addClass('visible');
    });
  }, function(event){
    $form.stop(true,true);
    if($form.has(':input:focus').length==0){
      to = setTimeout(function(){
        hideForm();
      }, 500);
    } else {
      jQuery(document).one('keyup', function(event){  
        if(event.keyCode==27){ 
          hideForm();
        }
      });
    }
  });  
  
  jQuery('#login-retrieve').submit(function(event){
    var $this   = jQuery(this);
    var $notice = $this.find('.notice span');
    var ret=true;
    var $mail = $this.find(':text');
    var errTxt = '';
    if($mail.val()==''){
      ret=false;
      errTxt = "Tu sais ce que c'est un mail!?";
    } else if (!com.lolita.utils.isValidMail($mail.val())){
      errTxt = "Tss tss tss le mail n'est pas valide...";
      ret=false;
    }
    
    $notice.text(errTxt);
    if(!ret){
      event.stopPropagation();
      event.cancelBubble = true;
      jQuery.map([$mail,$notice],function($el){
        $el.effect('pulsate',{times: 5},2000,function(){
          $mail.focus();
        });
      });
      
      //$notice.effect('pulsate',{times: 5},2000);
    }
    return ret;
  });
  
});
